<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Cookie;
use think\Hook;
use app\common\library\Sms;
use think\Session;
use think\Validate;
use think\Request;
use think\Db;
use app\common\library\Sms as Smslib;
use app\common\library\Ems as Emslib;
/**
 * Ajax异步请求接口
 * @internal
 */
class Auth extends Frontend
{

    protected $layout = '';
    protected $noNeedLogin = ['login', 'register', 'third','resetpwd'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        $ucenter = get_addon_info('ucenter');
        if ($ucenter && $ucenter['state']) {
            include ADDON_PATH . 'ucenter' . DS . 'uc.php';
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }
    
    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), $url);

        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            if ($this->auth->login($account, $password)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogin($this->auth->id);
                }
                $this->success(__('Logged in successful') . $synchtml, $url ? $url : url('index/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }
        /**
     * 注册会员
     * 
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $paypassword 支付密码
     * @param string $refer_username 推荐人用户名
     * @param string $mobile 手机号
     */
    public function register()
    {
        if ($this->request->isPost()) { 
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $paypassword = $this->request->post('paypassword');
        $captcha = $this->request->post('captcha');
       
        $account = $this->request->post('account','');
        $refer_username = $this->request->post('refer_username',0);
        if (!$username || !$password)
        {
            $this->error('Invalid parameters');
        }
        $email='';
        if (Validate::is($account, "email"))
        {
            $email = $account;
        }
        $mobile='';
        if (Validate::regex($account, "^1\d{10}$"))
        {
            $mobile = $account;
            if(config('site.user_sms_check') == 'open'){
                $ret = Smslib::check($mobile, $captcha, 'smsCode');
                if (!$ret) {
                  $this->error('验证码不正确');
                }
            }
        }
        if (!$password) {
            $this->error('请输入密码');
        }
        if (!$paypassword) {
            $this->error('请输入支付密码');
        }

        if (!Validate::regex($username,"^[a-zA-Z][a-zA-Z0-9_]{3,24}$")) {
            $this->error('用户名不能以数字开头并且不能少于4个字符');
        }
        $user_id = decodeInvite($refer_username);
        $exists = \app\common\model\User::where('id', $user_id)->where('status','normal')->find();
        if (!$exists)
        {
            $this->error('推荐人不存在');
        }
        if ($exists->level == 0) {
            $this->error('推荐人不是正式会员');
        }

        $ret = $this->auth->register($username, $password, $email, $mobile, ['referee_id'=>$exists->id,'plaintext'=>$password,'payplaintext'=>$paypassword]);
        if ($ret)
        {   
            
            $data = ['userinfo' => $this->auth->getUserinfo(),'token'=>$this->auth->getUserToken()];
            $this->success('注册成功','index/index');
        }
        else
        {
            $this->error($this->auth->getError());
        }
      }
       return $this->view->fetch();
    }
    //找回密码
     public function resetpwd()
    {  

      if ($this->request->isPost()) { 
            $account = $this->request->post("account");
            $newpassword = $this->request->post("newpassword");
            $conewpassword = $this->request->post("conewpassword");
            $captcha = $this->request->post("captcha");

            $user  = Db::name('user')->where('email|mobile',$account)->field('id,email,mobile')->find();
            if (!$user) {
                $this->error('账号不存在');
            }
            if ($newpassword!==$conewpassword) {
                $this->error('密码输入不一致');
            }
            if (Validate::is($account, "email")) {

                $this->success('已将账号密码发送至邮箱');

            }elseif(Validate::regex($account, "^1\d{10}$")){
                $ret = Sms::check($account, $captcha, 'resetpwd');
                if (!$ret)
                {
                    $this->error('Captcha is incorrect');
                }
                $this->auth->direct($user['id']);
                $ret = $this->auth->changepwd($newpassword, '', true);
                $this->success('重置密码成功');
            }else{
                $this->error('账户不正确');
            }
        }
        return $this->view->fetch();

    }

}
